import 'dart:async';

import 'package:cashbook/utils/manager.dart';
import 'package:flutter/material.dart';

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SplashState();
  }
}

class SplashState extends State<SplashPage> {
  Timer _countdownTimer;
  var showText = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    Manager.instance.isLogin = true;
    countDown2();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(width: 1, color: Colors.red),
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: Text('${showText}'),
        ),
      ),
    );
  }

  //方式二
  void countDown2() {
    if (null != _countdownTimer) {
      _countdownTimer.cancel();
    }
    _countdownTimer = new Timer.periodic(new Duration(seconds: 3), (timer) {
      var time = 4 - _countdownTimer.tick;
      setState(() {
        showText = '${time}s后进入';
      });
      if (time == 1 || time <= 0) {
        _countdownTimer.cancel();
        _countdownTimer = null;
        goLoginPage();
      }
    });
  }

  //方式一
  void countDown() {
    var _duration = Duration(seconds: 4);
    Future.delayed(_duration, goLoginPage);
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  void goLoginPage() {
    try {
      Navigator.pushNamedAndRemoveUntil(
          context, '/login', (route) => route == null);
    } catch (e) {
      print(e);
    }
  }
}
